<?php
/**
 * 智能表单功能
 * Enter description here ...
 * @author nijn
 *
 */
class AutoForm extends  CComponent{

	public  $model;
	protected $config;
	
	public function init() {
		
	}
	
	public function run($model) {
		$this->model = $model;
		static $htmlArr = array();
		foreach ($this->getAttributesArr() as $key => $val) {
			$htmlArr[] = $this->renderHtml($key, $val);
		}
		
		return $htmlArr;
	}
	
	/**
	 * 获取需要渲染的字段数组
	 * Enter description here ...
	 */
	public function getAttributesArr($subModel = '', $relationName = '') {
		static $htmlAttributes = array();
		$obj = is_object($subModel) ? $subModel : $this->model;
		$attributes = array();
		$data = $this->getConfig();
		if (empty($data)) {
			// 过滤字段
			$data = AutoFormDictionary::filterAttributes($obj->attributeNames());
		}
		foreach ($data as $key => $val) {
			$keyName = is_array($val) ? $key : $val;
			$keyName = is_object($subModel) ? $relationName .'.'.$keyName : $keyName;
			if (is_array($val)) {
				$attributes[$keyName] = $val;
			} else {
				$attributes[$keyName] = array('TextInput');
			}
			
		}
		$htmlAttributes = array_merge($htmlAttributes,AutoFormDictionary::autoInput($attributes));
		foreach ($obj->cascade as $one) {
			$relations = $obj->getMetadata()->relations;
			$subModel = new $relations[$one]->className;
			$this->getAttributesArr($subModel, $one);
		}
		//渲染字段返回
		return $htmlAttributes;
	}
	
	
	/**
	 * 渲染表单页面
	 * Enter description here ...
	 * @param unknown_type $attribute
	 * @param unknown_type $text
	 * @param unknown_type $htmlOptions
	 */
	public function renderHtml($attribute,$parameters) {
		$htmlArr = array();
		$form = new CActiveFormAdv();
		$htmlArr['label'] = $form->LabelEx($this->model, $attribute);
		$htmlArr['input'] = $this->createInput($form, $attribute, $parameters);
		$htmlArr['error'] = $form->error($this->model, $attribute);
		
		return $htmlArr;
	}
	
	/**
	 * 创建input文本
	 * Enter description here ...
	 * @param unknown_type $array
	 */
	protected function createInput($form, $attribute, $parameters) {
		$inputType = array_shift($parameters);
		return  CFormInputFactory::input($inputType, $form, $this->model, $attribute, $parameters);
	}
	
	/**
	 * 获取配置
	 * Enter description here ...
	 */
	public function getConfig() {
		if (empty($this->config)) {
			$fileName = get_class($this->model);
			$file = Yii::app()->basePath."/config/{$fileName}.php";
			if (is_file($file)) $this->config =  include $file;
			else $this->config = array();
		}
		return $this->config;
	}
	
}

?>